package gemini.castor.ui.client.page.content.store.catalog.categorycatalog;

import gemini.basic.model.ProductType;
import gemini.castor.ui.client.ServiceCatalog;
import gemini.castor.ui.client.mvp.callback.AbstractAsyncCallback;
import gemini.castor.ui.client.mvp.single.CastorWidgetDisplay;
import gemini.castor.ui.client.mvp.single.CastorWidgetPresenter;
import gemini.castor.ui.client.page.RootEvent;
import gemini.castor.ui.client.page.content.store.catalog.CatalogEvent;
import gemini.castor.ui.client.utils.GuiUtils;
import gemini.castor.ui.client.utils.PlaceConstants;

import java.util.ArrayList;
import java.util.List;

import ch.elca.gwt.mvp.client.EventBus;
import ch.elca.gwt.mvp.client.place.Place;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.inject.Inject;

public class CategoryCatalogPresenter extends
		CastorWidgetPresenter<CategoryCatalogPresenter.Display> {

	@Inject
	public CategoryCatalogPresenter(Display display, EventBus globalEventBus) {
		super(display, globalEventBus);
	}

	public interface Display extends CastorWidgetDisplay {
		void setProductTypes(List<ProductType> productTypes);
		HasClickHandlers getViewProductsClickHandlers();
		ProductType getCategory();
	}
	
	private Object outputObject;

	public static final Place PLACE = new Place(PlaceConstants.PLACE_CATALOG);

	@Override
	protected void onBind() {
		registerHandler(display.getViewProductsClickHandlers().addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent event) {
				outputObject = display.getCategory();
				localEventBus.fireEvent(new CatalogEvent(CatalogEvent.ForwardType.VIEW_PRODUCTS));
			}
		}));
		
		eventBus.fireEvent(new RootEvent(RootEvent.ForwardType.MASK));
		ServiceCatalog.getProductTypeService().getAllCategory(
				new AbstractAsyncCallback<ArrayList<ProductType>>() {

					@Override
					public void onSuccess(ArrayList<ProductType> result) {
						eventBus.fireEvent(new RootEvent(RootEvent.ForwardType.UN_MASK));
						if (result != null) {
							display.setProductTypes(result);
							display.loadData();
						} else {
							GuiUtils.alert("Cannot find any product type in db");
						}
					}
				});
	}

	@Override
	public Place getPlace() {
		return PLACE;
	}
	
	@Override
	public Object getOutputObject(){
		return outputObject;
	}
}
